<!-- UserEdit.vue -->
<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { useUserStore } from '@/stores/userStore.js'
import { ElMessage } from 'element-plus'
import RoleListView from '@/components/RoleList/indexView.vue'
import { RoleApi } from '@/api/role/index.js'

const userStore = useUserStore()
const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  }
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  mobile: '',
  userType: '',
  deptId: '',
  roleIds: [] // 添加角色ID字段
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}
// 监听用户数据变化，填充表单
watch(
    () => props.userData,
    (newUserData) => {
      if (newUserData) {
        Object.keys(form).forEach(key => {
          // 密码字段特殊处理：不显示原有密码
          if (key === 'password') {
            form[key] = '';
            return;
          }

          if (newUserData[key] !== undefined) {
            form[key] = newUserData[key]
          }
        })
      }
    },
    { immediate: true }
)

const handleClose = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()

  try {
    loading.value = true
    // 准备提交的数据
    const submitData = { ...form }

    // 如果密码为空，则不更新密码
    if (!submitData.password) {
      delete submitData.password
    }

    // 确保ID字段存在
    if (!submitData.id) {
      throw new Error('用户ID不能为空')
    }

    // 调用更新用户的 API
    await userStore.updateUser(submitData)
    ElMessage.success('用户信息更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('更新用户失败:', error)
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}


</script>

<template>
  <el-dialog
      :model-value="visible"
      title="编辑用户"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        v-loading="loading"
    >
      <el-form-item label="用户ID" prop="id">
        <el-input v-model="form.id" disabled/>
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名"/>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="留空则不修改密码" show-password/>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"/>
      </el-form-item>

      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入手机号"/>
      </el-form-item>

      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="form.userType" placeholder="请选择用户类型" style="width: 100%">
          <el-option label="普通用户" value="USER"/>
          <el-option label="律师" value="LAWYER"/>
          <el-option label="管理员" value="ADMIN"/>
        </el-select>
      </el-form-item>

      <el-form-item label="部门ID" prop="deptId">
        <el-input v-model="form.deptId" placeholder="请输入部门ID"/>
      </el-form-item>

      <el-form-item label="角色" prop="roleIds">
        <RoleListView v-model="form.roleIds" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
